package com.utility.sh1;

import java.security.MessageDigest;
import java.util.Collections;
import java.util.List;

/**
 * SHA1签名工具
 * @author 林建波
 */
public class SHAUtility {
	/**
	 * 对字符串进行sha1签名
	 * @param source
	 * @return
	 */
	public static String sign(String source){
		try{
			MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");  
			messageDigest.update(source.getBytes("UTF-8"));
			byte messageBytes[] = messageDigest.digest(); 
			StringBuffer hexString = new StringBuffer();
			for(byte messageByte : messageBytes){
				String shaHex = Integer.toHexString(messageByte & 0xFF);  
                if (shaHex.length() < 2) {  
                    hexString.append(0);  
                }  
                hexString.append(shaHex);  
			}
            return hexString.toString();
		}catch(Exception e){
			return "";
		}
	}
	
	/**
	 * 对集合进行sha1签名
	 * 首先对集合中的值进行字符串的字典排序
	 * 然后将集合中的值拼接成一个字符串，并对字符串进行签名
	 * @param source
	 * @return
	 */
	public static String sign(List<String> sourceList){
		if(sourceList == null || sourceList.isEmpty()){
			return "";
		}
		Collections.sort(sourceList);  
		StringBuilder source = new StringBuilder();
		for(String s : sourceList){
			source.append(s);
		}
		return sign(source.toString());
	}
	public static void main(String[] args) {
		System.out.println(sign("我们的祖国是发大水发撒的发士大夫撒范德萨的发"));
	}
}
